package com.restaurant.ressys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.restaurant.ressys.entity.Category;
import com.restaurant.ressys.entity.Food;
import com.restaurant.ressys.service.CategoryService;
import com.restaurant.ressys.service.FoodService;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhangsan
 * @since 2022-02-28
 */
@RestController
@RequestMapping("/food")
public class FoodController {
    @Resource
    private FoodService foodService;
    @Resource
    private CategoryService cs;
    @GetMapping("/selectAll")
    public List<Food> selectAll(){
       return foodService.list();
    }
    @GetMapping("/selectByCid")
    public List<Food> selectByCid(int cid){
        QueryWrapper<Food> wrapper=new QueryWrapper<>();
        wrapper.eq("cid",cid);
        return foodService.list(wrapper);
    }
    @PostMapping("/add")
    public void add(@RequestBody Food food){
        foodService.save(food);
    }
    @DeleteMapping("/del/{id}")
    public void delete(@PathVariable("id") int id){
        foodService.removeById(id);
    }
    @Value("${attachPath}")
    private String path;
    @PostMapping("/uploadAttach")
    public String uploadAttach(MultipartFile attach) throws IOException {
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        String oldName=attach.getOriginalFilename();//获取到上传的文件的原始文件名
        String newName = UUID.randomUUID().toString()+oldName;
        attach.transferTo(new File(path,newName));
        return newName;
    }
    @GetMapping("/selectOne/{id}")
    public Food selectOne(@PathVariable("id") int id){
        Food food = foodService.getById(id);
        Category category = cs.getById(food.getCid());
        food.setCategory(category);
        return food;
    }
}

